package com.qdxwx.web.controller.picture;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.member.MemberRecordService;
import com.qdxwx.data.service.picture.PictureService;
import com.qdxwx.data.service.user.UserCountService;
import com.qdxwx.data.service.user.UserDownloadService;
import com.qdxwx.models.member.MemberRecord;
import com.qdxwx.models.picture.Picture;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
@RequestMapping("/picture")
public class PictureDownloadController extends BaseController {
    @Autowired
    private PictureService pictureService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private UserDownloadService userDownloadService;

    /**
     * 下载
     */
    @RequestMapping(value = {"/download.json"})
    @ResponseBody
    public AjaxResult Download(HttpServletRequest request) throws IOException {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.auth("此功能需要登录才能下载");
        }
        int pictureId = TKConvert.toInteger(request.getParameter("id"));
        Picture picture = pictureService.get(pictureId);
        if (picture == null) {
            return AjaxResult.error("找不到指定素材");
        }
        MemberRecord member = null;
        if (picture.getImgWidth() > 1024) {
            member = memberRecordService.getValidByUserId(user.getUserId(), 1);
            if (member == null) {
                return AjaxResult.forbid("该素材是高清图片，原图仅限本网素材VIP用户查看或下载！");
            }
        }
        AjaxResult jsonResult = userCountService.checkPictureLimit(user.getUserId(),member != null);
        if(jsonResult.getCode() > 0){
            return AjaxResult.error(jsonResult.getMsg());
        }
        pictureService.updateDown(picture.getId());
        userDownloadService.create(picture, user);
        userCountService.updatePictureDownCount(user.getUserId(),1);

        return AjaxResult.success(picture.getImgUrl(), 1);
    }
}
